package com.sne.airways.basecore.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: skyline{http://my.oschina.net/skyline520}
 * Date: 12-11-27
 * Time: 上午11:15
 * To change this template use File | Settings | File Templates.
 */
public class JSONUtils {
    private final static String ENCODING_PREFIX = "encoding:";
    private final static String NOCACHE_PREFIX = "no-cache:";
    private final static String ENCODING_DEFAULT = "UTF-8";
    private final static boolean NOCACHE_DEFAULT = true;
    private final static String DATEPATTERN = "yyyy-MM-dd";
    private final static String DATETIMEPATTERN = "yyyy-MM-dd HH:mm:ss";

    private final static Logger logger = Logger.getLogger(JSONUtils.class);
    private static JsonConfig jsonConfig = new JsonConfig();

    /**
     * 获取session
     * @return session
     */
    public static HttpSession getHttpSession() {
        return CommonUtils.getRequest().getSession();
    }

    /**
     * 获取request
     * @return request
     */
    public static HttpServletRequest getRequest() {
        return CommonUtils.getRequest();
    }

    /**
     * 获取response
     * @return response
     */
    public static HttpServletResponse getResponse() {
        return CommonUtils.getResponse();
    }

    /**
     * 输出内容
     * render("text/plain", "hello", "encoding:GBK");
     * render("text/plain", "hello", "no-cache:false");
     * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
     * @param contentType 类型
     * @param content 输出内容
     * @param headers 可变的header数组，目前接受的值为"encoding:"或"no-cache:",见示例代码.
     * 不设置时候默认UTF-8和true
     */
    public static void render(final String contentType, final String content, final String... headers) {
        try {
            String encoding = ENCODING_DEFAULT;
            boolean noCache = NOCACHE_DEFAULT;
            for (String header : headers) {
                String headerName = StringUtils.substringBefore(header, ":");
                String headerValue = StringUtils.substringAfter(header, ":");

                if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
                    encoding = headerValue;
                } else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
                    noCache = Boolean.parseBoolean(headerValue);
                } else{
                    throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
                }
            }

            HttpServletResponse response = getResponse();
            String fullContentType = contentType + ";charset=" + encoding;
            response.setContentType(fullContentType);
            if (noCache) {
                response.setHeader("Pragma", "No-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
            }
            response.getWriter().write(content);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 输出text
     * @param text 输出内容
     * @param headers headers
     */
    public static void renderText(final String text, final String... headers) {
        render("text/plain", text, headers);
    }

    /**
     * 输出html
     * @param html html
     * @param headers headers
     */
    public static void renderHtml(final String html, final String... headers) {
        render("text/html", html, headers);
    }

    /**
     * 输出xml
     * @param xml xml字符串
     * @param headers headers
     */
    public static void renderXml(final String xml, final String... headers) {
        render("text/xml", xml, headers);
    }

    /**
     * 输出json
     * @param string json字符串
     * @param headers headers
     */
    public static void renderJson(final String string, final String... headers) {
        render("application/json", string, headers);
    }

    /**
     * 输出json字符串
     * @param object object对象
     * @param headers headers
     */
    public static void renderJson(final Object object, final String... headers) {
        jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor());
        JSONObject jsonObject = JSONObject.fromObject(object,jsonConfig);
        renderJson(jsonObject.toString(), headers);
    }

    /**
     * 输出json字符串
     * @param object object对象
     * @param excludes ignore忽视的属性
     * @param headers headers
     */
    public static void renderJson(final Object object,final String[] excludes, final String... headers) {
        jsonConfig.setExcludes(excludes);
        JSONObject jsonObject = JSONObject.fromObject(object,jsonConfig);
        renderJson(jsonObject.toString(), headers);
    }

    /**
     * 输出jsonarray
     * @param object object
     * @param headers headers
     */
    public static void renderJsonArray(final Object object, final String... headers) {
        jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor());
        JSONArray jsonArray = JSONArray.fromObject( object,jsonConfig);
        renderJson(jsonArray.toString(), headers);
    }

    /**
     * 输出jsonarray
     * @param object object
     * @param excludes ignore忽视的属性
     * @param headers headers
     */
    public static void renderJsonArray(final Object object,final String[] excludes, final String... headers) {
        jsonConfig.setExcludes(excludes);
        jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor());
        JSONArray jsonArray = JSONArray.fromObject( object,jsonConfig );
        renderJson(jsonArray.toString(), headers);
    }

    /**
     * 输出如下json对象{root:data,totalProperty:total}
     * @param object 数据?
     * @param totalProperty 数据总数量
     * @param headers headers
     */
    public static void renderPageJsonArray(final Object object,final Integer totalProperty,final String... headers){
        jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor());
        JSONArray jsonArray = JSONArray.fromObject(object,jsonConfig);
        renderJson("{root:"+jsonArray.toString()+",totalProperty:"+totalProperty+"}",headers);
    }

    /**
     * 输出如下json对象{root:data,totalProperty:total}
     * @param object 数据
     * @param excludes 忽视的属性
     * @param totalProperty 数据总数量
     * @param headers headers
     */
    public static void renderPageJsonArray(final Object object,final String[] excludes,final Integer totalProperty,final String... headers){
        jsonConfig.setExcludes(excludes);
        jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor());
        JSONArray jsonArray = JSONArray.fromObject(object,jsonConfig);
        renderJson("{root:"+jsonArray.toString()+",totalProperty:"+totalProperty+"}",headers);
    }

    /**
     * 输出成功标志
     */
    public static void renderSuccess(){
        renderJson("{success:true}");
    }
    /**
     * 输出成功标志
     */
    public static void renderSuccess(Object object,String msg){
        JSONObject jsonObject = JSONObject.fromObject(object);
        renderJson("{success:true,msg:"+msg+",data:"+jsonObject.toString()+"}");
    }

    /**
     * 输出成功标志
     */
    public static void renderSuccess(Object object){
        JSONObject jsonObject = JSONObject.fromObject(object);
        renderJson("{success:true,data:"+jsonObject.toString()+"}");
    }

    /**
     * 输出失败标志
     * @param message 错误信息
     */
    public static void renderFailure(String message){
        renderJson("{success:false,msg:'"+message+"'}");
    }

}
